/* eslint-disable consistent-return */
/* eslint-disable func-names */
/**
 * 异步选择组件
 */
import React, { useState, useEffect, forwardRef } from 'react';
import PropTypes from 'prop-types';

import { Spin, message, Select } from 'antd';

import { fetch } from '../../../common/api';
import { log } from '../../../common/tool';

const { Option } = Select;

// 封装组件
const AjaxSelect = forwardRef((props, ref) => {
    const [loading, setLoading] = useState(false);
    const [listData, setListData] = useState([]);

    useEffect(() => {
        handleGetList();
    }, []);

    const handleGetList = () => {
        const { urls, apiPath, apiData, apiMethod, listName } = props;
        setLoading(true);
        fetch({ urls, apiPath, apiData, apiMethod })
            .then((data) => {
                setLoading(false);
                setListData(data.data);
            })
            .catch(function (err) {
                log.error(err);
                message.error(`获取${listName}失败:${err.message}`);
            });
    };

    const handleChange = (key) => {
        const { value, listValueKey, listNameKey, onChange } = props;
        if (Array.isArray(value)) {
            if (!key) return onChange(['', '']);
            let label;
            listData.some(function (item) {
                if (item[listValueKey].toString() === key) {
                    label = item[listNameKey];
                    return true;
                }
                return false;
            });
            onChange([key, label]);
        } else {
            onChange(key || '');
        }
    };

    const { value, listName, listValueKey, listNameKey, disabled } = props;
    let selectValue;
    if (Array.isArray(value)) {
    // eslint-disable-next-line prefer-destructuring
        selectValue = value[0];
    } else {
        selectValue = value;
    }

    return (
        <Spin spinning={loading} className="app-ajax-select">
            <Select
                showSearch
                optionFilterProp="children"
                value={selectValue}
                onChange={handleChange}
                placeholder={`选择${listName}`}
                notFoundContent={`未找到${listName}`}
                allowClear
                disabled={disabled}
                ref={ref}
            >
                <Option value="" title={`选择${listName}`}>
          选择{listName}
                </Option>
                {listData.map((item, index) => (
                    <Option key={index} value={item[listValueKey].toString()} title={item[listNameKey]}>
                        {item[listNameKey]}
                    </Option>
                ))}
            </Select>
        </Spin>
    );
});

AjaxSelect.propTypes = {
    apiPath: PropTypes.string.isRequired, // API接口
    apiData: PropTypes.object, // api请求附加的数据
    apiMethod: PropTypes.string, // api请求method
    listName: PropTypes.string.isRequired, // 缺省列表名称
    listValueKey: PropTypes.string.isRequired, // 列表值的key值
    listNameKey: PropTypes.string.isRequired, // 列表名称key值
    value: PropTypes.oneOfType([
    // 值,支持字符串和数组形式
        PropTypes.string, // key值
        PropTypes.array, // [key, label]形式
    ]),
    onChange: PropTypes.func, // 获取值变化函数
    disabled: PropTypes.bool,
};

export default AjaxSelect;
